package com.starnet.yarnmonitor.security.filter;

import com.alibaba.fastjson.JSON;
import com.starnet.yarnmonitor.security.utils.JwtLoginToken;
import com.starnet.yarnmonitor.yarn.vo.result.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)  {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //创建未认证的凭证。此时凭证中主题principal为用户名
        JwtLoginToken jwtLoginToken = new JwtLoginToken(username, password);
        //将认证详情ip sessionid写道凭证
        jwtLoginToken.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication=null;
        try {  authentication = this.getAuthenticationManager().authenticate(jwtLoginToken);
        } catch (Exception e){
            response.setContentType("application/json;charset=UTF-8");
            Result result = Result.fail(e.getMessage());
            try {
                response.getWriter().write(JSON.toJSONString(result));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
     

        return authentication;
    }
}
